﻿
using B.S.Ingredients.APIRead.Application.Command.Products;
using B.S.Ingredients.Domain;
using B.S.Ingredients.ErrorCode;
using B.S.Ingredients.Infartructrue.Interfaces;
using MediatR;
using System.Transactions;

namespace B.S.Ingredients.APIRead.Application.CommandHandler.ProductHandler
{
    public class ProdictExportCommandHandler : IRequestHandler<ProdictExportCommand, APIResult<List<Product>>>
    {
        public ProdictExportCommandHandler(IBaseRepository<Product> productRepository,IBaseRepository<ExportClass> exportRepository)
        {
            ProductRepository = productRepository;
            ExportRepository = exportRepository;
        }

        public IBaseRepository<Product> ProductRepository { get; }
        public IBaseRepository<ExportClass> ExportRepository { get; }

        public async Task<APIResult<List<Product>>> Handle(ProdictExportCommand request, CancellationToken cancellationToken)
        {
            using (var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    await ExportRepository.CreateAsync(request.Data);

                    var path = ProductRepository.GetAll();
                    return new APIResult<List<Product>>
                    {
                        Data = path.ToList(),
                        Code = ResultCode.success,
                        Mag = "Export Success"
                    };

                }
                catch (Exception)
                {

                    throw;
                }
            }
        }
    }
}
